<template>
  <div class="form-table-container">
    <!-- 表单 -->
    <FormPage
      ref="tableFormPage"
      :config="formConfig"
      :rowData.sync="rowData"
      :current-id.sync="currentFormId"
      :tableIds.sync="formTableRowIds"
      @backEvent="formBackEvent"
      @lastNextRow="formLastNextRow"
    />

    <!-- table 表格数据信息 -->
    <div class="form-table-grid">
      <el-tabs v-model="activeTabs" @tab-click="tabClick">
        <el-tab-pane
          v-for="(tabsItem, tabsIndex) in gridTabs"
          :key="tabsIndex"
          :name="tabsItem.name"
          @on-change="tabClick"
        >
          <template slot="label">
            <div class="tab-pane-label">
              {{ tabsItem.label }}
            </div>
          </template>
          <!-- grid toolbar 表格工具栏 -->
          <div
            class="table-grid-toolbar"
            v-if="tabsItem.toolbarBtns && tabsItem.toolbarBtns.length > 0"
          >
            <div v-for="(btnItem, btnIndex) in tabsItem.toolbarBtns" :key="btnIndex">
              <div v-if="!btnItem.more">
                <el-button
                  v-if="
                    (!btnItem.showCondition || btnItem.showCondition(rowData)) &&
                    $btnPermission.verify(btnItem.permission)
                  "
                  size="small"
                  :type="btnItem.type"
                  :disabled="btnItem.onDisabled && btnItem.onDisabled(rowData)"
                  @click="customBtnClick(btnItem.click, btnItem.confirm, tabsItem)"
                >
                  <div v-if="btnItem.iconName" class="custom-btn-svg">
                    <svg-icon
                      :icon-class="btnItem.iconName"
                      :style="`color: ${btnItem.iconColor}};`"
                    ></svg-icon>
                  </div>
                  <div :class="btnItem.iconName ? 'custom-btn-name' : ''">
                    {{ btnItem.name }}
                  </div>
                </el-button>
              </div>
              <div class="toolbar-custom-more" v-if="btnItem.more">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    <svg-icon icon-class="btn-more"></svg-icon>
                    {{ btnItem.name }}
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="(moreItem, moreIndex) in btnItem.more"
                      :key="moreIndex"
                      :disabled="btnItem.onDisabled && btnItem.onDisabled(rowData)"
                    >
                      <div
                        class="more-menu-btn"
                        @click="
                          customBtnClick(moreItem.click, moreItem.confirm, tabsItem)
                        "
                        v-if="
                          (!moreItem.showCondition || moreItem.showCondition(rowData)) &&
                          $btnPermission.verify(moreItem.permission)
                        "
                      >
                        <div
                          v-if="moreItem.iconName"
                          class="menu-btn-svg"
                          :class="moreItem.iconName ? 'more-menu-margin' : ''"
                        >
                          <svg-icon
                            :icon-class="moreItem.iconName"
                            :style="`color: ${moreItem.iconColor}};`"
                          ></svg-icon>
                        </div>
                        <div class="menu-btn-name">
                          {{ moreItem.name }}
                        </div>
                      </div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
          </div>
          <!-- table grid page 表格页面 -->
          <div class="table-grid-page">
            <div v-if="tabsItem.type === 'grid'">
              <!-- 表格 -->
              <TablePage
                :ref="tabsItem.name"
                :customTableHeight="tabsItem.height"
                :pagination="tabsItem.pagination"
                :loading.sync="tabsItem.loading"
                :table-data="tabsItem.tableData"
                :formGrid="tabsItem"
                :formRowId="formCurrentRowId"
                :gridRefreshFun="refreshGridTable"
                :formData="rowData"
                :columns="tabsItem.columns"
                @reloadData="
                  loadTableData(
                    tabsItem,
                    tabsItem.realoadTableData,
                    tabsItem.name,
                    tabsItem.api,
                    formCurrentRowId
                  )
                "
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import FormPage from "@/components/FormPage/index.vue";
import TablePage from "@/components/TablePage/index.vue";

export default {
  name: "FormTablePage",
  components: {
    FormPage,
    TablePage,
  },
  props: {
    formConfig: {
      type: Object,
      default: () => {},
    },
    formRowData: {
      type: Object,
      default: () => {},
    },
    formCurrentRowId: {
      type: [Number, String],
      default: () => null,
    },
    formTableRowIds: {
      type: Array,
      default: () => [],
    },
    gridActiveTabs: {
      type: String,
      default: () => "",
    },
    formGridTabs: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    rowData: {
      get() {
        return this.formRowData ? this.formRowData : {};
      },
    },
    gridTabs: {
      get() {
        if (!this.formGridTabs || this.formGridTabs.length <= 0) {
          throw "tabs not empty!";
        }
        const activeGridTab = this.formGridTabs.filter(
          (item) => item.name === this.activeTabs
        )[0];
        this.loadTableData(
          activeGridTab,
          activeGridTab.realoadTableData,
          activeGridTab.name,
          activeGridTab.api,
          this.formCurrentRowId
        );
        return this.formGridTabs;
      },
    },
    activeTabs: {
      get() {
        if (!this.formGridTabs || this.formGridTabs.length <= 0) {
          throw "tabs not empty!";
        }
        const activeName = this.gridActiveTabs
          ? this.gridActiveTabs
          : this.formGridTabs
          ? this.formGridTabs[0].name
          : "";
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.activeTabName = activeName;
        return activeName;
      },
      set(val) {
        this.activeTabName = val;
      },
    },
    currentFormId: {
      get() {
        return this.formCurrentRowId;
      },
      set(val) {
        this.formDataId = val;
      },
    },
  },
  data() {
    return {
      formDataId: null,
      activeTabName: null,
    };
  },
  methods: {
    // 返回事件（返回到列表）
    formBackEvent() {
      this.$emit("formBackEvent");
    },

    // 上下一条
    formLastNextRow(currentRowId, loading) {
      this.$nextTick(() => {
        this.formDataId = currentRowId;
        console.log("测试", this.activeTabName);
        const activeGridTab = this.formGridTabs.filter(
          (item) => item.name === this.activeTabName
        )[0];
        this.$emit(
          "formLastNextRow",
          currentRowId,
          this.formConfig,
          activeGridTab,
          this.refreshGridTable,
          loading
        );
      });
    },

    // 表格重新加载数据
    loadTableData(_this, callback, ref, api, formId) {
      if (!callback || typeof callback !== "function") {
        return;
      }
      this.$nextTick(() => {
        callback(_this, this.$refs[ref], api, formId, this.$refs[_this.name][0].page);
      });
    },

    // 自定义按钮事件
    async customBtnClick(callback, confirm, _this) {
      if (!callback || typeof callback !== "function") {
        this.$message.error("按钮未绑定任何事件");
        return;
      }
      // 二次确认
      if (confirm) {
        this.$confirm(confirm.message, confirm.title, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            await this.customCallback(callback, _this);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消操作",
            });
          });
      } else {
        await this.customCallback(callback, _this);
      }
    },

    async customCallback(callback, _this) {
      const loading = this.$loading({
        lock: true,
        text: "正在操作中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      await callback(this.formCurrentRowId, this.refreshGridTable, _this);
      loading.close();
    },

    // 切换tabs刷新数据
    tabClick(e) {
      console.log(e, this.activeTabName);
      this.refreshGridTable();
    },

    // 刷新当前grid table
    refreshCurrentGridTable() {
      this.refreshGridTable();
    },

    // 刷新子表格
    refreshGridTable(gridTab) {
      this.$nextTick(() => {
        let activeGridTab = this.formGridTabs.filter(
          (item) => item.name === this.activeTabName
        )[0];
        if (gridTab) {
          activeGridTab = gridTab;
        }
        if (activeGridTab) {
          this.loadTableData(
            activeGridTab,
            activeGridTab.realoadTableData,
            activeGridTab.name,
            activeGridTab.api,
            this.formCurrentRowId
          );
        }
      });
    },

    // 刷新所有表格
    refreshAllGridTable() {
      this.formGridTabs.filter((item) => {
        this.loadTableData(
          item,
          item.realoadTableData,
          item.name,
          item.api,
          this.formCurrentRowId
        );
      });
    },

    // 重置表单
    reloadTableFormPage() {
      this.$nextTick(() => {
        // 刷新form表单
        this.$refs.tableFormPage.reloadFormPage();
        // 刷新表格
        this.refreshAllGridTable();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.form-table-container {
  padding: 0px;
  margin: 0px;

  .form-table-grid {
    border-top-style: dotted;
    border-top-width: 2px;
    border-top-color: #d7dde9;
    border-spacing: 1px;

    .el-tabs__header {
      .tab-pane-label {
        font-weight: bold;
        font-size: 17px;
      }
    }

    .table-grid-toolbar {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      margin-bottom: 20px;

      .el-button {
        margin-right: 15px;
        position: relative;

        .custom-btn-svg {
          position: absolute;
          left: 5px;
        }

        .custom-btn-name {
          margin-left: 5px;
        }
      }

      .toolbar-custom-more {
        background-color: #f0f0f0;
        padding-left: 5px;
        padding-right: 5px;
        width: 100px;
        text-align: center;
        height: 32px;
        line-height: 32px;

        .svg-icon {
          margin-right: 5px;
        }

        .el-dropdown-link {
          cursor: pointer;
          color: #132638;
        }

        .el-icon-arrow-down {
          font-size: 12px;
        }
      }
    }

    .table-grid-toolbar::after {
      content: "";
      position: absolute;
      top: 40px;
      left: 0;
      width: 100%;
      height: 1px;
      background-color: #00aaef;
    }
  }
}
</style>
